<template>
  <view class="my-donations-page">
    <!-- 顶部自定义导航 -->
    <tn-nav-bar fixed alpha customBack>
      <view slot="back" class="tn-custom-nav-bar__back" @click="goBack">
        <text class="icon tn-icon-left"></text>
      </view>
    </tn-nav-bar>

    <!-- 顶部横幅 -->
    <view class="header-banner">
      <image
        class="banner-img"
        src="/static/donate.jpg"
        mode="aspectFill"
      ></image>
      <view class="banner-overlay"></view>
      <view class="banner-content">
        <text class="banner-title">我的捐款</text>
        <text class="banner-subtitle">感谢您的每一份爱心</text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-wrapper">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-number">{{ totalDonations }}</text>
          <text class="stats-label">累计捐款次数</text>
        </view>
        <view class="stats-divider"></view>
        <view class="stats-item">
          <text class="stats-number">¥{{ formatNumber(totalAmount) }}</text>
          <text class="stats-label">累计捐款金额</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 筛选选项 -->
      <view class="filter-wrapper">
        <view class="filter-tabs">
          <view
            v-for="(tab, index) in filterTabs"
            :key="index"
            class="filter-tab"
            :class="{ active: activeFilter === tab.value }"
            @click="setFilter(tab.value)"
          >
            <text class="filter-tab-text">{{ tab.label }}</text>
          </view>
        </view>
      </view>

      <!-- 捐款记录列表 -->
      <view class="records-list">
        <view v-if="filteredRecords.length === 0" class="empty-state">
          <image
            class="empty-icon"
            src=""
            mode="aspectFit"
          ></image>
          <text class="empty-text">暂无捐款记录</text>
        </view>

        <view
          v-for="(record, index) in filteredRecords"
          :key="index"
          class="record-item"
          @click="viewDetail(record)"
        >
          <view class="record-header">
            <view class="project-info">
              <text class="project-name">{{ record.projectName }}</text>
              <text class="donation-time">{{
                formatDate(record.createTime)
              }}</text>
            </view>
            <view class="amount-info">
              <text class="amount">¥{{ formatNumber(record.amount) }}</text>
              <view class="status-badge" :class="record.status">
                <text class="status-text">{{
                  getStatusText(record.status)
                }}</text>
              </view>
            </view>
          </view>

          <view v-if="record.message" class="record-message">
            <text class="message-text">{{ record.message }}</text>
          </view>

          <view class="record-footer">
            <text class="record-id">订单号：{{ record.id }}</text>
            <text v-if="record.isAnonymous" class="anonymous-tag">匿名</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
      
      <!-- 加载中状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
const templatePageMixin = require("@/libs/mixin/template_page_mixin.js");
import { getMyDonationsList, getDonationStatistics } from '@/appApi/my-donations.js';

export default {
  mixins: [templatePageMixin],
  data() {
    return {
      filterTabs: [
        { label: "全部", value: "all" },
        { label: "已完成", value: "completed" },
        { label: "处理中", value: "processing" },
        { label: "已取消", value: "cancelled" },
      ],
      activeFilter: "all",
      hasMore: true,
      donationRecords: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      totalDonations: 0,
      totalAmount: 0,
    };
  },
  onLoad() {
    this.loadStatistics();
    this.loadDonationRecords();
  },
  computed: {
    filteredRecords() {
      if (this.activeFilter === "all") {
        return this.donationRecords;
      }
      return this.donationRecords.filter(
        (record) => record.paymentStatus === this.activeFilter
      );
    },
  },
  methods: {
    // 加载统计信息
    async loadStatistics() {
      try {
        const response = await getDonationStatistics();
        console.log('统计信息响应:', response);
        
        // 处理不同的响应格式
        let data = null;
        if (response && response.code === 200 && response.data) {
          data = response.data;
        } else if (response && response.data) {
          data = response.data;
        } else if (response && typeof response === 'object') {
          data = response;
        }
        
        if (data) {
          this.totalDonations = data.totalDonations || 0;
          this.totalAmount = data.totalAmount || 0;
        }
      } catch (error) {
        console.error('加载统计信息失败:', error);
      }
    },
    
    // 加载捐款记录
    async loadDonationRecords(reset = true) {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        if (reset) {
          this.pageNum = 1;
          this.donationRecords = [];
        }
        
        const params = {
          status: this.activeFilter,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        
        const response = await getMyDonationsList(params);
        console.log('捐款记录响应:', response);
        
        let rows = [];
        
        // 处理不同的响应格式
        if (response && response.rows) {
          rows = response.rows;
        } else if (response && Array.isArray(response.data)) {
          rows = response.data;
        } else if (response && Array.isArray(response)) {
          rows = response;
        }
        
        if (rows.length > 0) {
          const newRecords = rows.map(record => ({
            id: record.orderNo || record.donationId,
            donationId: record.donationId,
            projectName: record.activityName || '未知项目',
            amount: record.amount || 0,
            status: record.paymentStatus || 'pending',
            paymentStatus: record.paymentStatus || 'pending',
            createTime: record.createTime || record.paymentTime,
            message: record.donationMessage || '',
            isAnonymous: record.isAnonymous === 1,
          }));
          
          if (reset) {
            this.donationRecords = newRecords;
          } else {
            this.donationRecords.push(...newRecords);
          }
          
          // 判断是否还有更多数据
          this.hasMore = newRecords.length === this.pageSize;
          if (!reset && newRecords.length > 0) {
            this.pageNum++;
          }
        } else if (reset) {
          // 如果是重置查询且没有数据，清空记录
          this.donationRecords = [];
          this.hasMore = false;
        }
      } catch (error) {
        console.error('加载捐款记录失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 设置筛选条件
    setFilter(filter) {
      this.activeFilter = filter;
      this.loadDonationRecords(true);
    },
    
    formatNumber(num) {
      if (!num) return '0';
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      const date = new Date(dateStr);
      const now = new Date();
      const diff = now.getTime() - date.getTime();
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));

      if (days === 0) {
        return "今天";
      } else if (days === 1) {
        return "昨天";
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return date.toLocaleDateString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
        });
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        completed: "已完成",
        processing: "处理中",
        cancelled: "已取消",
        paid: "已完成",
        pending: "处理中",
        refunded: "已退款"
      };
      return statusMap[status] || status;
    },
    
    viewDetail(record) {
      uni.showModal({
        title: "捐款详情",
        content: `项目：${record.projectName}\n金额：¥${this.formatNumber(record.amount)}\n时间：${
          this.formatDate(record.createTime)
        }\n状态：${this.getStatusText(record.status)}${
          record.message ? "\n留言：" + record.message : ""
        }`,
        showCancel: false,
        confirmText: "确定",
      });
    },
    
    loadMore() {
      if (!this.hasMore || this.loading) {
        uni.showToast({
          title: "没有更多数据了",
          icon: "none",
        });
        return;
      }
      
      this.pageNum++;
      this.loadDonationRecords(false);
    },
  },
};
</script>

<style lang="scss" scoped>
.my-donations-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 自定义导航栏返回按钮样式 */
.tn-custom-nav-bar__back {
  width: 60%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 1000rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  color: #ffffff;
  font-size: 18px;

  .icon {
    display: block;
    flex: 1;
    margin: auto;
    text-align: center;
  }
}

// 顶部横幅
.header-banner {
  position: relative;
  width: 100%;
  height: 300rpx;
  overflow: hidden;

  .banner-img {
    width: 100%;
    height: 100%;
  }

  .banner-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      180deg,
      rgba(22, 122, 70, 0.4) 0%,
      rgba(22, 122, 70, 0.7) 100%
    );
  }

  .banner-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .banner-title {
      font-size: 44rpx;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 16rpx;
      text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
    }

    .banner-subtitle {
      font-size: 28rpx;
      color: #ffffff;
      text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
    }
  }
}

// 统计信息
.stats-wrapper {
  padding: 0 30rpx;
  margin-top: -40rpx;
  position: relative;
  z-index: 2;

  .stats-card {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 40rpx 30rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);

    .stats-item {
      flex: 1;
      text-align: center;

      .stats-number {
        display: block;
        font-size: 40rpx;
        font-weight: bold;
        color: rgb(22, 122, 70);
        margin-bottom: 8rpx;
      }

      .stats-label {
        font-size: 24rpx;
        color: #666666;
      }
    }

    .stats-divider {
      width: 2rpx;
      height: 60rpx;
      background-color: #e5e5e5;
      margin: 0 30rpx;
    }
  }
}

// 内容区域
.content-wrapper {
  padding: 40rpx 30rpx 0;
}

// 筛选选项
.filter-wrapper {
  margin-bottom: 30rpx;

  .filter-tabs {
    display: flex;
    background: #ffffff;
    border-radius: 12rpx;
    padding: 8rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .filter-tab {
      flex: 1;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 8rpx;
      transition: all 0.3s;

      &.active {
        background: rgb(22, 122, 70);

        .filter-tab-text {
          color: #ffffff;
        }
      }

      .filter-tab-text {
        font-size: 26rpx;
        color: #666666;
        font-weight: 500;
      }
    }
  }
}

// 记录列表
.records-list {
  .empty-state {
    text-align: center;
    padding: 100rpx 0;

    .empty-icon {
      width: 120rpx;
      height: 120rpx;
      margin-bottom: 30rpx;
    }

    .empty-text {
      font-size: 26rpx;
      color: #999999;
    }
  }

  .record-item {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    }

    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;

      .project-info {
        flex: 1;

        .project-name {
          display: block;
          font-size: 30rpx;
          font-weight: bold;
          color: #333333;
          margin-bottom: 8rpx;
        }

        .donation-time {
          font-size: 24rpx;
          color: #999999;
        }
      }

      .amount-info {
        text-align: right;

        .amount {
          display: block;
          font-size: 32rpx;
          font-weight: bold;
          color: rgb(22, 122, 70);
          margin-bottom: 8rpx;
        }

        .status-badge {
          display: inline-block;
          padding: 4rpx 12rpx;
          border-radius: 20rpx;
          font-size: 20rpx;

          &.completed {
            background: rgba(22, 122, 70, 0.1);
            .status-text {
              color: rgb(22, 122, 70);
            }
          }

          &.processing {
            background: rgba(255, 165, 0, 0.1);
            .status-text {
              color: #ff9500;
            }
          }

          &.cancelled {
            background: rgba(255, 59, 48, 0.1);
            .status-text {
              color: #ff3b30;
            }
          }
        }
      }
    }

    .record-message {
      background: #f8f9fa;
      border-radius: 8rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;

      .message-text {
        font-size: 26rpx;
        color: #666666;
        line-height: 1.5;
      }
    }

    .record-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .record-id {
        font-size: 22rpx;
        color: #999999;
      }

      .anonymous-tag {
        background: rgba(153, 153, 153, 0.1);
        color: #999999;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        font-size: 20rpx;
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 40rpx 0;

  .load-more-text {
    font-size: 26rpx;
    color: #666666;
  }
}

.loading-state {
  text-align: center;
  padding: 40rpx 0;

  .loading-text {
    font-size: 26rpx;
    color: #999999;
  }
}
</style>
